
<script setup>
import { defineProps, ref, watchEffect } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import {AddQuestion, EditQuestion, ListQuestionVOByPage} from "@/api/question.js";
import AIGenerateQuestion from "@/components/question/AIGenerateQuestion.vue";
import {GetApp} from "@/api/app.js";
// import AiGenerateQuestionDrawer from "@/views/add/components/AiGenerateQuestionDrawer.vue";

const props = defineProps({
  appId: {
    type: String,
    default: ""
  }
});
const app = ref({
  appName: "",
  appDesc: "",
});
const router = useRouter();

// 题目内容结构（理解为题目列表）
const questionContent = ref([]);

/**
 * 添加题目
 * @param index
 */
const addQuestion = (index) => {
  questionContent.value.splice(index, 0, {
    title: "",
    options: []
  });
};

/**
 * 删除题目
 * @param index
 */
const deleteQuestion = (index) => {
  questionContent.value.splice(index, 1);
};

/**
 * 添加题目选项
 * @param question
 * @param index
 */
const addQuestionOption = (question, index) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 0, {
    key: "",
    value: "",
    result: "",
    score: 0
  });
};

/**
 * 删除题目选项
 * @param question
 * @param index
 */
const deleteQuestionOption = (question, index) => {
  if (!question.options) {
    question.options = [];
  }
  question.options.splice(index, 1);
};

const oldQuestion = ref(null);

/**
 * 加载数据
 */
const loadData = async () => {
  if (!props.appId) {
    console.log("appId为空");
    return;
  }
  console.log("appId不为空 ",props.appId);
  const app_data = await GetApp(props.appId);
  app.value ={
    ...app_data.data,
  }
  console.log("app_data: ",app.value);
  //这里需要替换为实际的API调用
  const res = await ListQuestionVOByPage({
    appId: props.appId,
    current: null,
    pageSize: null,
    sortField: "createTime",
    sortOrder: "desc",
  });
  console.log("res: ",res);
  if (res.code === 0 && res.data?.questionContent) {
    oldQuestion.value = res.data?.questionContent;
    console.log("oldQuestion: ",oldQuestion.value);

    // 清空或初始化 questionContent
    questionContent.value = [];

    // 遍历 oldQuestion 并解析每个 questionContent
    for (let i = 0; i < oldQuestion.value.length; i++) {
      try {
        // 解析 JSON 字符串为 JavaScript 对象
        const parsedContent = JSON.parse(oldQuestion.value[i].questionContent);
        const ProperContent = parsedContent.map(question=>{
          const updateOption = question.options.map(option=>{
            return{
              ...option,
              result: option.result===''?null:option.result,
              score: option.score ===''?null:option.score,
            };
          })
          return {
            ...question,
            options: updateOption,
          }
        });
        console.log("ProperContent: ",ProperContent)
        // 将解析后的内容添加到 questionContent
        if (Array.isArray(ProperContent)) {
          questionContent.value = questionContent.value.concat(ProperContent);
        } else {
          console.warn(`Question content at index ${i} is not an array:`, ProperContent);
        }
      } catch (error) {
        console.error(`Failed to parse question content at index ${i}:`, error);
      }
    }
  } else {
    ElMessage.error("获取数据失败");
  }
};

// 获取旧数据
watchEffect(() => {
  loadData();
});

/**
 * 提交
 */
const handleSubmit = async () => {
  if (!props.appId || !questionContent.value) {
    return;
  }
  let params = {
    questionContent: questionContent.value,
  }
  if(oldQuestion.value[0]?.id){
    params ={
      id: oldQuestion.value[0]?.id,
      ...params,
    }
    await EditQuestion(params);
  }else {
    params = {
      appId: props.appId,
      ...params,
    };
    const data = await AddQuestion(params);
  }
  // 模拟提交成功
  ElMessage.success("操作成功，即将跳转到应用详情页");
  setTimeout(() => {
    router.push(`/mainPage/app/detail/${props.appId}`);
  }, 2000);
};
/**
 * AI生成题目子组件
 */
const childRef = ref(null)
const handleOpenDrawer = ()=>{
  console.log("11111")
  if(childRef.value){
    console.log("22222")
    childRef.value.openDrawer();
  }
}
/**
 * 获取AI生成的题目
 */
const handleAIGenerateSuccess = (data) => {
  questionContent.value = questionContent.value.concat(data);
}
/**
 * SSE 开始生成
 * @param event
 */
const onSSEStart = (event) => {
  ElMessage.success("开始生成");
};

/**
 * SSE 生成完毕
 * @param event
 */
const onSSEClose = (event) => {
  ElMessage.success("生成完毕");
};

const question_size = ref(40)
</script>
<template>
  <div id="addQuestionPage">
    <el-card>
<!--      <h1>{{questionContent}}</h1>-->
      <h2 style="margin-bottom: 32px">设置题目</h2>
      <el-form
          :model="questionContent"
          :style="{ width: '800px' }"
          label-position="left"
          @submit.prevent="handleSubmit"
      >
        <el-form-item label="应用 id">
          <span>{{ appId }}</span>
        </el-form-item>
        <el-form-item label="应用名称">
          <span>{{ app.appName }}</span>
        </el-form-item>
        <el-form-item label="应用描述">
          <span>{{ app.appDesc }}</span>
        </el-form-item>
        <el-form-item label="题目列表">
          <el-space size="large">
            <div class="add-question-button-container">
              <el-button @click="addQuestion(questionContent.length)">
                底部添加题目
              </el-button>
            </div>
            <div class="add-question-button-container">
              <el-button @click="handleOpenDrawer" type="primary">
                AI生成题目
              </el-button>
              <AIGenerateQuestion ref="childRef" :app="app" @generateQuestion="handleAIGenerateSuccess"/>
            </div>
          </el-space>
          <div class="question-list">
            <div v-for="(question, index) in questionContent" :key="index" class="question-item">
              <div class="question-header">
                <h3>题目 {{ index + 1 }}</h3>
                <el-space size="large">
                  <el-button size="small" @click="addQuestion(index + 1)">
                    添加题目
                  </el-button>
                  <el-button
                      size="small"
                      type="danger"
                      @click="deleteQuestion(index)"
                  >
                    删除题目
                  </el-button>
                </el-space>
              </div>
              <el-form-item :label="`题目 ${index + 1} 标题`">
                <el-input v-model="question.title" placeholder="请输入标题" />
              </el-form-item>

              <div class="options-section">
                <div class="options-header">
                  <h4>题目 {{ index + 1 }} 选项列表</h4>
                  <el-button
                      size="small"
                      @click="addQuestionOption(question, question.options.length)"
                  >
                    底部添加选项
                  </el-button>
                </div>

                <div
                    v-for="(option, optionIndex) in question.options"
                    :key="optionIndex"
                    class="option-item"
                >
                  <div class="option-header">
                    <span>选项 {{ optionIndex + 1 }}</span>
                    <el-space size="large">
                      <el-button
                          size="small"
                          @click="addQuestionOption(question, optionIndex + 1)"
                      >
                        添加选项
                      </el-button>
                      <el-button
                          size="small"
                          type="danger"
                          @click="deleteQuestionOption(question, optionIndex)"
                      >
                        删除选项
                      </el-button>
                    </el-space>
                  </div>

                  <div class="option-fields">
                    <el-form-item label="选项 key" class="form-field">
                      <el-input v-model="option.key" placeholder="请输入选项 key" />
                    </el-form-item>
                    <el-form-item label="选项值" class="form-field">
                      <el-input v-model="option.value" placeholder="请输入选项值" />
                    </el-form-item>
                    <el-form-item label="选项结果" class="form-field">
                      <el-input v-model="option.result" placeholder="请输入选项结果" />
                    </el-form-item>
                    <el-form-item label="选项得分" class="form-field">
                      <el-input
                          v-model="option.score"
                          :min="0"
                          placeholder="请输入选项得分"
                      />
                    </el-form-item>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit" style="width: 120px">
            提交
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
#addQuestionPage {
  font-family: Arial, sans-serif;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

#addQuestionPage h2 {
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

#addQuestionPage h3 {
  color: #606266;
  font-size: 18px;
  margin: 16px 0;
}

#addQuestionPage h4 {
  color: #909399;
  font-size: 16px;
  margin: 12px 0;
}

.add-question-button-container {
  margin-bottom: 20px;
}

.question-list {
  width: 100%;
}

.question-item {
  width: 100%;
  margin-bottom: 24px;
  padding: 16px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.question-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.options-section {
  margin-top: 16px;
  padding: 12px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.options-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.option-item {
  margin-bottom: 16px;
  padding: 12px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.option-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.option-fields {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.form-field {
  margin-bottom: 0;
}

.form-field :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
}

.form-field :deep(.el-input),
.form-field :deep(.el-input-number) {
  width: 100%;
}
</style>